﻿using System;
using System.Net;


namespace WebCamDeskLib
{
    public class DownloadEventArgs : EventArgs
    {
        public DownloadEventArgs(string s)
        {
            message = s;
        }
        private string message;
        public string Message
        {
            get{return message;}
            set{message = value;}
        }
    }

    public class DownloadProgressEventArgs : EventArgs
    {
        public DownloadProgressEventArgs(decimal aPercent)
        {
            percent = aPercent;
        }
        private decimal percent;
        public decimal Percent
        {
            get { return percent; }
            set { percent = value; }
        }
    }
    public class Downloader
    {
        private string fFileName;
        public Downloader()
        {
            
        }
                                 
        public void DownloadFile(string aUrl, string aFileName) 
        {
            fFileName = aFileName;
            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadFileCompleted += completed;
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DowwnloadProgressChanged);
                webClient.DownloadFileAsync(new Uri(aUrl), aFileName);
            }

        }

        public event EventHandler<DownloadEventArgs> RaiseDownloadCompleteEvent;
        public event EventHandler<DownloadProgressEventArgs> RaiseDownloadPercentEvent;
        
        void DowwnloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            EventHandler<DownloadProgressEventArgs> handler = RaiseDownloadPercentEvent;
            if (handler != null)
            {
                handler(this, new DownloadProgressEventArgs(e.ProgressPercentage));
            }
        }

        void completed(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            EventHandler<DownloadEventArgs> handler = RaiseDownloadCompleteEvent;
            if (handler != null)
            {
                
                handler(this, new DownloadEventArgs(fFileName));
            }
            
        }

    }
}
